package com.fishingwithme.android.ui.viewmodels

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fishingwithme.android.data.model.MyHarvestDto
import com.fishingwithme.android.data.model.MySpotDto
import com.fishingwithme.android.data.repository.FishingRepository
import kotlinx.coroutines.flow.firstOrNull

class MyHarvestPagingSource(
    private val repository: FishingRepository
) : PagingSource<Int, MyHarvestDto>() {

    override fun getRefreshKey(state: PagingState<Int, MyHarvestDto>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MyHarvestDto> {
        val page = params.key ?: 1
        return try {

            val response = repository.getMyHarvestPage(page, params.loadSize).firstOrNull()

            
            // Handle the case where response is null
            if (response == null) {
                return LoadResult.Error(Exception("No data received"))
            }
            
            // Since we're using Result type, we need to check if it's success or failure
            return if (response.isSuccess) {
                val pageResponse = response.getOrNull()
                if (pageResponse != null) {

                    val data = pageResponse.records ?: emptyList()
                    val prevKey = if (page == 1) null else page - 1
                    // Fix nextKey calculation: check if we have more records based on total
                    val nextKey = if (pageResponse.total != null &&
                        pageResponse.current != null &&
                        pageResponse.size != null &&
                        pageResponse.current * pageResponse.size < pageResponse.total) {
                        page + 1
                    } else {
                        null
                    }

                    LoadResult.Page(
                        data = data,
                        prevKey = prevKey,
                        nextKey = nextKey
                    )
                } else {
                    LoadResult.Error(Exception("Empty page response"))
                }
            } else {
                val error = response.exceptionOrNull()

                LoadResult.Error(error ?: Exception("Unknown error"))
            }
        } catch (e: Exception) {

            LoadResult.Error(e)
        }
    }
}